<template>
  <div class="user-menu">
    <!-- 未登录状态 -->
    <div v-if="!userStore.isLoggedIn" class="auth-buttons">
      <n-button
        text
        size="medium"
        @click="showLoginModal = true"
        class="auth-btn login-btn"
      >
        登录
      </n-button>
      <n-button
        type="primary"
        size="medium"
        @click="showRegisterModal = true"
        class="auth-btn register-btn"
      >
        注册
      </n-button>
    </div>

    <!-- 已登录状态 -->
    <div v-else class="user-info">
      <n-dropdown
        :options="userMenuOptions"
        @select="handleMenuSelect"
        placement="bottom-end"
        trigger="hover"
      >
        <div class="user-trigger">
          <UserAvatar
            :user="userStore.userInfo"
            :size="isMobile ? 32 : 36"
            clickable
            show-status
          />
          <div v-if="!isMobile" class="user-text">
            <div class="username">{{ userStore.nickname }}</div>
            <div class="user-level">{{ formatUserLevel() }}</div>
          </div>
          <n-icon :size="16" class="dropdown-icon">
            <ChevronDownOutline />
          </n-icon>
        </div>
      </n-dropdown>
    </div>

    <!-- 登录模态框 -->
    <n-modal
      v-model:show="showLoginModal"
      preset="card"
      title="用户登录"
      :style="{ width: isMobile ? '90%' : '400px' }"
      :mask-closable="true"
      :close-on-esc="true"
    >
      <LoginForm
        @success="handleLoginSuccess"
        @switch-to-register="switchToRegister"
        @forgot-password="showForgotPasswordModal = true"
      />
    </n-modal>

    <!-- 注册模态框 -->
    <n-modal
      v-model:show="showRegisterModal"
      preset="card"
      title="用户注册"
      :style="{ width: isMobile ? '90%' : '400px' }"
      :mask-closable="true"
      :close-on-esc="true"
    >
      <RegisterForm
        @success="handleRegisterSuccess"
        @switch-to-login="switchToLogin"
      />
    </n-modal>

    <!-- 找回密码模态框 -->
    <n-modal
      v-model:show="showForgotPasswordModal"
      preset="card"
      title="找回密码"
      :style="{ width: isMobile ? '90%' : '400px' }"
      :mask-closable="true"
      :close-on-esc="true"
    >
      <ForgotPasswordForm
        @success="handleForgotPasswordSuccess"
        @back-to-login="showForgotPasswordModal = false"
      />
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, h, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import UserAvatar from './UserAvatar.vue'
import LoginForm from './LoginForm.vue'
import RegisterForm from './RegisterForm.vue'
import ForgotPasswordForm from './ForgotPasswordForm.vue'
import {
  ChevronDownOutline,
  PersonOutline,
  SettingsOutline,
  HeartOutline,
  LogOutOutline,
  ShieldCheckmarkOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()
const userStore = useUserStore()

// 响应式状态
const isMobile = ref(false)
const showLoginModal = ref(false)
const showRegisterModal = ref(false)
const showForgotPasswordModal = ref(false)

// 检查移动端
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})

// 用户菜单选项
const userMenuOptions = computed(() => [
  {
    label: '个人中心',
    key: 'profile',
    icon: () => h(PersonOutline)
  },
  {
    label: '我的收藏',
    key: 'favorites',
    icon: () => h(HeartOutline)
  },
  {
    label: '账户设置',
    key: 'settings',
    icon: () => h(SettingsOutline)
  },
  {
    type: 'divider',
    key: 'divider'
  },
  {
    label: '退出登录',
    key: 'logout',
    icon: () => h(LogOutOutline)
  }
])

// 格式化用户等级
const formatUserLevel = () => {
  const user = userStore.userInfo
  if (!user) return ''
  
  // 这里可以根据实际业务逻辑计算用户等级
  const score = user.score || 0
  if (score >= 10000) return 'VIP'
  if (score >= 5000) return '高级用户'
  if (score >= 1000) return '活跃用户'
  return '新手'
}

// 处理菜单选择
const handleMenuSelect = async (key: string) => {
  switch (key) {
    case 'profile':
      router.push('/user/center?tab=profile')
      break
    case 'favorites':
      router.push('/user/center?tab=favorites')
      break
    case 'settings':
      router.push('/user/center?tab=settings')
      break
    case 'logout':
      await handleLogout()
      break
  }
}

// 处理登出
const handleLogout = async () => {
  try {
    await userStore.logout()
    message.success('已退出登录')
    // 如果当前在需要登录的页面，跳转到首页
    if (router.currentRoute.value.meta?.requiresAuth) {
      router.push('/')
    }
  } catch (error) {
    console.error('登出失败:', error)
    message.error('登出失败，请重试')
  }
}

// 处理登录成功
const handleLoginSuccess = () => {
  showLoginModal.value = false
  message.success('登录成功')
}

// 处理注册成功
const handleRegisterSuccess = () => {
  showRegisterModal.value = false
  message.success('注册成功')
}

// 处理找回密码成功
const handleForgotPasswordSuccess = () => {
  showForgotPasswordModal.value = false
  message.success('密码重置成功，请重新登录')
  showLoginModal.value = true
}

// 切换到注册
const switchToRegister = () => {
  showLoginModal.value = false
  showRegisterModal.value = true
}

// 切换到登录
const switchToLogin = () => {
  showRegisterModal.value = false
  showLoginModal.value = true
}
</script>

<style scoped>
.user-menu {
  display: flex;
  align-items: center;
}

/* 认证按钮 */
.auth-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.auth-btn {
  font-weight: 500;
}

.login-btn {
  color: var(--n-text-color);
}

.register-btn {
  border-radius: 20px;
  padding: 0 16px;
}

/* 用户信息 */
.user-info {
  position: relative;
}

.user-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.user-trigger:hover {
  background-color: var(--n-hover-color);
}

.user-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: var(--n-text-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
}

.user-level {
  font-size: 12px;
  color: var(--n-text-color-2);
  white-space: nowrap;
}

.dropdown-icon {
  color: var(--n-text-color-3);
  transition: transform 0.2s ease;
}

.user-trigger:hover .dropdown-icon {
  transform: rotate(180deg);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .auth-buttons {
    gap: 6px;
  }
  
  .auth-btn {
    font-size: 14px;
    padding: 0 12px;
  }
  
  .register-btn {
    padding: 0 12px;
  }
  
  .user-trigger {
    gap: 6px;
    padding: 2px 6px;
  }
}

@media (max-width: 480px) {
  .auth-buttons {
    gap: 4px;
  }
  
  .auth-btn {
    font-size: 13px;
    padding: 0 10px;
  }
}
</style>
